//
//  IAPHelper.m
//  InAppRage
//
//  Created by Ray Wenderlich on 2/28/11.
//  Copyright 2011 Ray Wenderlich. All rights reserved.
//

#import "IAPHelper.h"

@implementation IAPHelper
@synthesize productIdentifiers = _productIdentifiers;
@synthesize products = _products;
@synthesize purchasedProducts = _purchasedProducts;
@synthesize request = _request;


//初始化代码将检测哪些产品已经被购买,哪些还没有(根据NSUserDefaults保存的信息判断),并设置适当的数据结构
- (id)initWithProductIdentifiers:(NSSet *)productIdentifiers {
    if ((self = [super init])) {
        
        // Store product identifiers
        _productIdentifiers = productIdentifiers ;
        
        // Check for previously purchased products
        NSMutableSet * purchasedProducts = [NSMutableSet set];
        for (NSString * productIdentifier in _productIdentifiers) {
            BOOL productPurchased = [[NSUserDefaults standardUserDefaults] boolForKey:productIdentifier];
            if (productPurchased) {
                [purchasedProducts addObject:productIdentifier];
                NSLog(@"Previously purchased: %@", productIdentifier);
            }
            NSLog(@"Not purchased: %@", productIdentifier);
        }
        self.purchasedProducts = purchasedProducts;
                        
    }
    return self;
}

//从iTunes Connect检索产品列表的方法
- (void)requestProducts {
    
    self.request = [[SKProductsRequest alloc] initWithProductIdentifiers:_productIdentifiers];
    _request.delegate = self;
    [_request start];
    
}

//产品列表查询完毕时(productsRequest:didReceiveResponse),它会收到一个回调消息
- (void)productsRequest:(SKProductsRequest *)request didReceiveResponse:(SKProductsResponse *)response {
    
    
//    它贮存产品列表并返回(是一个SKProducts的数组),
//    然后把request设置为nil(为了释放内存),
//    然后发出一个通知,任何侦听这个通知的对象都会收到这个消息
    NSLog(@"Received products results...");
    self.products = response.products;
    self.request = nil;    
    
    [[NSNotificationCenter defaultCenter] postNotificationName:kProductsLoadedNotification object:_products];    
}

- (void)recordTransaction:(SKPaymentTransaction *)transaction {    
    // TODO: Record the transaction on the server side...    
}

- (void)provideContent:(NSString *)productIdentifier {
    
    NSLog(@"Toggling flag for: %@", productIdentifier);
    [[NSUserDefaults standardUserDefaults] setBool:TRUE forKey:productIdentifier];
    [[NSUserDefaults standardUserDefaults] synchronize];
    [_purchasedProducts addObject:productIdentifier];
   /**严加明修改了地方*/
//    [[NSNotificationCenter defaultCenter] postNotificationName:kProductPurchasedNotification object:productIdentifier];
    
}

- (void)completeTransaction:(SKPaymentTransaction *)transaction {
    NSLog(@"completeTransaction...");
   
    [self recordTransaction: transaction];
    [self provideContent: transaction.payment.productIdentifier];
    [[SKPaymentQueue defaultQueue] finishTransaction: transaction];
    [[NSNotificationCenter defaultCenter] postNotificationName:kProductPurchasedNotification object:transaction];
}

- (void)restoreTransaction:(SKPaymentTransaction *)transaction {
    
    NSLog(@"restoreTransaction...");
    
    [self recordTransaction: transaction];
    [self provideContent: transaction.originalTransaction.payment.productIdentifier];
    [[SKPaymentQueue defaultQueue] finishTransaction: transaction];
    
}

- (void)failedTransaction:(SKPaymentTransaction *)transaction {
    
    if (transaction.error.code != SKErrorPaymentCancelled)
    {
        NSLog(@"Transaction error: %@", transaction.error.localizedDescription);
    }
    
    [[NSNotificationCenter defaultCenter] postNotificationName:kProductPurchaseFailedNotification object:transaction];
    
    [[SKPaymentQueue defaultQueue] finishTransaction: transaction];
    
}

//把此类当作delegate来接收支付事务的更新消息
//所以，当支付付完成或者失败的时候,paymentQueue:updatedTransactions 这个函数将会被调用。
- (void)paymentQueue:(SKPaymentQueue *)queue updatedTransactions:(NSArray *)transactions
{
    for (SKPaymentTransaction *transaction in transactions)
    {
        switch (transaction.transactionState)
        {
            case SKPaymentTransactionStatePurchased:
                [self completeTransaction:transaction];
                break;
            case SKPaymentTransactionStateFailed:
                [self failedTransaction:transaction];
                break;
            case SKPaymentTransactionStateRestored:
                [self restoreTransaction:transaction];
            default:
                break;
        }
    }
}
//- (void)paymentQueue:(SKPaymentQueue *)queue restoreCompletedTransactionsFailedWithError:(NSError *)error NS_AVAILABLE_IOS(3_0){
//    [[NSNotificationCenter defaultCenter] postNotificationName:kProductRePurchaseFailedNotification object:@""];
//    
//}
//
//// Sent when all transactions from the user's purchase history have successfully been added back to the queue.
- (void)paymentQueueRestoreCompletedTransactionsFinished:(SKPaymentQueue *)queue NS_AVAILABLE_IOS(3_0){
    
    if (0 >= [queue.transactions count]) {
        [[NSNotificationCenter defaultCenter] postNotificationName:kProductRePurchaseFailedNotification object:@""];
        
    }
}



- (void)buyProductIdentifier:(NSString *)productIdentifier {
    
    NSLog(@"Buying %@...", productIdentifier);
//    创建一个新的SKPayment对象,并且把这个对象加载到队列中去
    SKPayment *payment = [SKPayment paymentWithProductIdentifier:productIdentifier];
    [[SKPaymentQueue defaultQueue] addPayment:payment];
    
}
//#pragma mark - 🍐delegate
//// 交易结束
//- (void)completeTransaction:(SKPaymentTransaction *)transaction{
//    // Your application should implement these two methods.
//    NSString * productIdentifier = transaction.payment.productIdentifier;
//    NSString * receipt = [transaction.transactionReceipt base64EncodedString];
//    if ([productIdentifier length] > 0) {
//        // 向自己的服务器验证购买凭证
//    }
//
//    [self verifyPurchaseWithPaymentTransaction:transaction isTestServer:NO];
//}
//
//// 交易失败
//- (void)failedTransaction:(SKPaymentTransaction *)transaction{
//    if (transaction.error.code != SKErrorPaymentCancelled) {
//        [self handleActionWithType:SIAPPurchFailed data:nil];
//    }else{
//        [self handleActionWithType:SIAPPurchCancle data:nil];
//    }
//
//    [[SKPaymentQueue defaultQueue] finishTransaction:transaction];
//}
//
//- (void)verifyPurchaseWithPaymentTransaction:(SKPaymentTransaction *)transaction isTestServer:(BOOL)flag{
//    //交易验证
//    NSURL *recepitURL = [[NSBundle mainBundle] appStoreReceiptURL];
//    NSData *receipt = [NSData dataWithContentsOfURL:recepitURL];
//
//    if(!receipt){
//        // 交易凭证为空验证失败
//        [self handleActionWithType:SIAPPurchVerFailed data:nil];
//        return;
//    }
//    // 购买成功将交易凭证发送给服务端进行再次校验
//    [self handleActionWithType:SIAPPurchSuccess data:receipt];
//
//    NSError *error;
//    NSDictionary *requestContents = @{
//                                      @"receipt-data": [receipt base64EncodedStringWithOptions:0]
//                                      };
//    NSData *requestData = [NSJSONSerialization dataWithJSONObject:requestContents
//                                                          options:0
//                                                            error:&error];
//
//    if (!requestData) { // 交易凭证为空验证失败
//        [self handleActionWithType:SIAPPurchVerFailed data:nil];
//        return;
//    }
//
//    //In the test environment, use https://sandbox.itunes.apple.com/verifyReceipt
//    //In the real environment, use https://buy.itunes.apple.com/verifyReceipt
//
//    NSString *serverString = @"https://buy.itunes.apple.com/verifyReceipt";
//    if (flag) {
//        serverString = @"https://sandbox.itunes.apple.com/verifyReceipt";
//    }
//    NSURL *storeURL = [NSURL URLWithString:serverString];
//    NSMutableURLRequest *storeRequest = [NSMutableURLRequest requestWithURL:storeURL];
//    [storeRequest setHTTPMethod:@"POST"];
//    [storeRequest setHTTPBody:requestData];
//
//    NSOperationQueue *queue = [[NSOperationQueue alloc] init];
//    [NSURLConnection sendAsynchronousRequest:storeRequest queue:queue
//                           completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
//                               if (connectionError) {
//                                   // 无法连接服务器,购买校验失败
//                                   [self handleActionWithType:SIAPPurchVerFailed data:nil];
//                               } else {
//                                   NSError *error;
//                                   NSDictionary *jsonResponse = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
//                                   if (!jsonResponse) {
//                                       // 苹果服务器校验数据返回为空校验失败
//                                       [self handleActionWithType:SIAPPurchVerFailed data:nil];
//                                   }
//
//                                   // 先验证正式服务器,如果正式服务器返回21007再去苹果测试服务器验证,沙盒测试环境苹果用的是测试服务器
//                                   NSString *status = [NSString stringWithFormat:@"%@",jsonResponse[@"status"]];
//                                   if (status && [status isEqualToString:@"21007"]) {
//                                       [self verifyPurchaseWithPaymentTransaction:transaction isTestServer:YES];
//                                   }else if(status && [status isEqualToString:@"0"]){
//                                       [self handleActionWithType:SIAPPurchVerSuccess data:nil];
//                                   }
//#if DEBUG
//                                   NSLog(@"----验证结果 %@",jsonResponse);
//#endif
//                               }
//                           }];
//
//
//    // 验证成功与否都注销交易,否则会出现虚假凭证信息一直验证不通过,每次进程序都得输入苹果账号
//    [[SKPaymentQueue defaultQueue] finishTransaction:transaction];
//}
- (void)dealloc
{
//    [_productIdentifiers release];
    _productIdentifiers = nil;
//    [_products release];
    _products = nil;
//    [_purchasedProducts release];
    _purchasedProducts = nil;
//    [_request release];
    _request = nil;
//    [super dealloc];
}

@end
